import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Spin, InputNumber, Upload, Input, Calendar, Badge, Empty, Tooltip, Popover, Button, Tabs, Modal, Select, message, Pagination } from 'antd';
import moment from 'moment';
import { PrimaryC, PrimaryGhostC, NoQueryC, SecondHeaderC, DATA_ENTRY, AdvancedSearch, ModalC, TableC, FirstHeaderC } from '../../../comps';
import myStyle from './index.less';
const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { confirm } = Modal;
const { Option } = Select;
import { fixedNum } from '../../../utils/utils';
import uuid from 'es6-uuid';
import upImg from '../../../assets/busi/assetSplit/up_arrow.png';
import downImg from '../../../assets/busi/assetSplit/down_arrow.png';
import upSelectedImg from '../../../assets/busi/assetSplit/up_arrow_select.png';
import downSelectedImg from '../../../assets/busi/assetSplit/down_arrow_select.png';
@connect(({ initialSplitM, loading }) => ({
  initialSplitM,
  loading,
}))
@Form.create()
export default class AssignDiyC extends PureComponent {
  state = {
    columnsAssigned: undefined, //已分配
    dataSoureAssigned: undefined,
    seletedRowsUp: [], //上方选中行 已分配
    seletedRowsDown: [], //下方方选中行 未分配
    selectedRowKeysUp: undefined, //上方选中行index 已分配
    selectedRowKeysDown: undefined, //下方方选中行index 未分配
    columnsNoAssign: undefined, //未分配
    dataSoureNoAssign: undefined, //未分配
    assetProductRate: undefined, //资产组合收益率
    assignedProportion: undefined, //已分配比例
    dataSoureNoAssign_old: undefined, //保存调整前
  };
  componentDidMount() {
    this.setState({
      columnsNoAssign: JSON.parse(JSON.stringify(this.props.columnsNoAssign || [])),
      dataSoureNoAssign: JSON.parse(JSON.stringify(this.props.dataSoureNoAssign || [])),
      dataSoureNoAssign_old: JSON.parse(JSON.stringify(this.props.dataSoureNoAssign || [])),
    });
    this.queryAssignedAsset(this.props.modalData.productId);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.dataSoureNoAssign) != JSON.stringify(this.props.dataSoureNoAssign)) {
      this.setState({
        columnsNoAssign: JSON.parse(JSON.stringify(nextProps.columnsNoAssign || [])),
        dataSoureNoAssign: JSON.parse(JSON.stringify(nextProps.dataSoureNoAssign || [])),
        dataSoureNoAssign_old: JSON.parse(JSON.stringify(nextProps.dataSoureNoAssign || [])),
      });
    }
  }

  //根据子产品ID，获取已分配的资产信息
  queryAssignedAsset = (productId) => {
    this.props.dispatch({
      type: 'initialSplitM/queryAssignedAsset',
      payload: {
        productId: productId,
        currentPage: 1,
        numInPage: 5000,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item, key) => {
            item.key = uuid(8);
            item.isEdit = false;
            item.isOrigin = true;
            item.averageMarketVal = parseFloat(item.marketValue / item.allocation);
          });
          this.setState(
            {
              columnsAssigned: data.columns || [],
              dataSoureAssigned: JSON.parse(JSON.stringify(data.dataSource)),
              dataSourceAssignedOld: JSON.parse(JSON.stringify(data.dataSource)),
            },
            () => {
              this.tryCalc();
            },
          );
        } else {
          this.setState({
            columnsAssigned: [],
            dataSoureAssigned: [],
          });
        }
      },
    });
  };
  //点击编辑按钮 切换为编辑状态 显示保存按钮
  clickEdit = (type, record) => {
    const { dataSoureAssigned } = this.state;
    dataSoureAssigned.map((item) => {
      if (item.key == record.key) {
        item.isEdit = type == 'edit' ? true : false;
      }
    });
    this.setState({
      dataSoureAssigned: [...dataSoureAssigned],
    });
  };
  //点击保存按钮
  saveRow = (record) => {
    const { dataSoureNoAssign, dataSoureNoAssign_old, dataSoureAssigned } = this.state;
    if (record.allocation === 0 || record.allocation === undefined) {
      message.warning('数量必须大于0');
      return;
    }
    let msg;
    let currentRowOld = dataSoureNoAssign_old.find((item) => item.key == record.key);
    let currentRowEdit = dataSoureNoAssign.find((item) => item.key == record.key);

    dataSoureNoAssign.map((item) => {
      if (item.key == record.key) {
        if (!currentRowOld) return;
        if (currentRowOld.restNum - record.allocation < 0) {
          msg = '数量应小于对应资产的已分配和未分配的总和';
          message.warning(msg);
          return;
        } else {
          item.restNum = currentRowOld.restNum - record.allocation;
          //更新市值 市值=数量*平均市值  未分配数量/初始导入时数量=权重 未分配
          item.marketValue = parseFloat(item.restNum * item.averageMarketVal);
          item.weight = item.totalNum ? parseFloat(item.restNum / item.totalNum) : '--';
          msg = '通过';
        }
      }
    });
    if (msg == '通过') {
      //更新市值 市值=数量*平均市值  当前行的市值/所有的市值之和=权重 已分配
      record.marketValue = parseFloat(record.allocation * record.averageMarketVal);
      let sum = 0; //市值之和
      dataSoureAssigned.map((item) => {
        sum += item.marketValue;
      });
      dataSoureAssigned.map((item) => {
        item.weight = parseFloat(item.marketValue / sum);
      });

      this.setState({
        dataSoureNoAssign: [...dataSoureNoAssign],
        dataSoureAssigned: [...dataSoureAssigned],
      });
      this.clickEdit('save', record);
      return;
    }
    if (!msg) {
      this.clickEdit('save', record);
    }
  };
  //点击试算
  tryCalc = () => {
    const { dataSoureAssigned } = this.state;
    if (dataSoureAssigned && !dataSoureAssigned.length) return;
    if (dataSoureAssigned.findIndex((item) => item.isEdit == true) > -1) {
      message.warning('当前处于编辑状态!');
      return;
    }
    this.props.dispatch({
      type: 'initialSplitM/tryCalc',
      payload: {
        productId: this.props.modalData.productId,
        assignData: dataSoureAssigned.map((item) => {
          return { id: item.id, allocation: item.allocation };
        }),
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            assetProductRate: data.assetProductRate, //资产组合收益率
            assignedProportion: data.assignedProportion, //已分配比例
          });
        } else {
          this.setState({
            assetProductRate: undefined, //资产组合收益率
            assignedProportion: undefined, //已分配比例
          });
        }
      },
    });
  };
  //点击确定
  confirmCalc = () => {
    const { dataSoureAssigned } = this.state;
    if (dataSoureAssigned && !dataSoureAssigned.length) return;
    if (dataSoureAssigned.findIndex((item) => item.isEdit == true) > -1) {
      message.warning('当前处于编辑状态!');
      return;
    }
    this.props.dispatch({
      type: 'initialSplitM/confirmCalc',
      payload: {
        productId: this.props.modalData.productId,
        assignData: dataSoureAssigned.map((item) => {
          return { id: item.id, allocation: item.allocation };
        }),
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.props.triggleVisible(false, 'success');
        }
      },
    });
  };

  //已分配
  initTableAssigned = () => {
    const { columnsAssigned, dataSoureAssigned, selectedRowKeysUp } = this.state;
    const rowSelection = {
      //保存选中行
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ seletedRowsUp: selectedRows, selectedRowKeysUp: selectedRowKeys });
      },
      selectedRowKeys: selectedRowKeysUp,
      columnWidth: 50,
    };
    if (columnsAssigned && columnsAssigned[columnsAssigned.length - 1] && columnsAssigned[columnsAssigned.length - 1].key != 'operate') {
      columnsAssigned.push({
        key: 'operate',
        type: 'operate',
        title: '操作',
        // width:80,
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.clickEdit('edit', record);
            },
            rules: {
              hide: {
                relation: 'or',
                items: [
                  { key: 'isEdit', value: [true], relation: ['='] },
                  { key: 'isOrigin', value: [true], relation: ['='] },
                ],
              },
            },
          },
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveRow(record);
            },
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
            },
          },
        ],
      });
    }
    columnsAssigned &&
      columnsAssigned.map((item) => {
        if (item.key != 'operate') {
          item.width = parseFloat(86 / (columnsAssigned.length - 1)) + '%';
        }
        if (item.key == 'price' || item.key == 'marketValue') {
          item.type = 'money';
          if (item.key == 'price') {
            item.toFixed = 4;
          }
        }
        if (item.key == 'assetRate' || item.key == 'weight') {
          item.type = 'rate';
          if (item.key == 'assetRate') item.toFixed = 4;
        }
        if (item.key == 'allocation') {
          item.type = 'number';
          item.render = (text, record) => {
            if (record.isEdit) {
              return (
                <InputNumber
                  style={{ width: '100%' }}
                  min={0}
                  formatter={(value) => {
                    let temp = `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                    return `${temp}`;
                  }}
                  onChange={(e) => {
                    record.allocation = e;
                    dataSoureAssigned.map((row, i) => {
                      if (row.key == record.key) {
                        row = record;
                        dataSoureAssigned[i] = record;
                        this.setState({
                          dataSoureAssigned: [...dataSoureAssigned],
                        });
                      }
                    });
                  }}
                  value={record.allocation}
                />
              );
            } else {
              return text === 0 || text ? fixedNum(text, 2) : '--';
            }
          };
        }
      });

    return (
      <TableC
        columns={columnsAssigned}
        dataSource={dataSoureAssigned}
        rowSelection={{
          ...rowSelection,
        }}
        hidePage={true}
        scroll={dataSoureAssigned && dataSoureAssigned.length > 5 ? { x: '100%', y: '178px' } : {}}
        rowKey='key'
      />
    );
  };
  //未分配
  initTableNoAssign = () => {
    const { columnsNoAssign, dataSoureNoAssign, selectedRowKeysDown } = this.state;
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ seletedRowsDown: selectedRows, selectedRowKeysDown: selectedRowKeys });
      },
      selectedRowKeys: selectedRowKeysDown,
      columnWidth: 50,
    };
    columnsNoAssign &&
      columnsNoAssign.map((item) => {
        if (item.key == 'restAmount') {
          item.title = '成本价';
        }
        if (item.key != 'assetName') {
          item.width = parseFloat(86 / (columnsNoAssign.length - 1)) + '%';
        }
        if (item.key == 'restAmount') {
          item.width = '10%';
        }
        if (item.key == 'restAmount' || item.key == 'marketValue') {
          item.type = 'money';
          if (item.key == 'restAmount') {
            item.toFixed = 4;
          }
        }
        if (item.key == 'assetRate' || item.key == 'weight') {
          item.type = 'rate';
          if (item.key == 'assetRate') item.toFixed = 4;
        }
        if (item.key == 'restNum') {
          item.align = 'right';
          item.render = (text) => {
            return !text && text !== 0 ? '--' : fixedNum(text, 2);
          };
        }
      });
    return (
      <TableC
        columns={columnsNoAssign}
        dataSource={dataSoureNoAssign}
        hidePage={true}
        rowSelection={{
          ...rowSelection,
        }}
        scroll={dataSoureNoAssign && dataSoureNoAssign.length > 5 ? { x: '100%', y: '178px' } : {}}
        rowKey='key'
      />
    );
  };
  //点击向下箭头
  onClickDown = () => {
    const { seletedRowsUp, dataSoureNoAssign, dataSoureAssigned } = this.state;
    if (!seletedRowsUp.length) return;
    if (dataSoureAssigned.findIndex((item) => item.isEdit == true) > -1) {
      message.warning('当前处于编辑状态!');
      return;
    }
    seletedRowsUp.map((row) => {
      //找出当前选中的资产在已分配资产数组中的index位置 ，为了移动之后，删除该行 点击试算之后，已分配的key全部重置，所以比较资产code
      let selectIndex = dataSoureAssigned.findIndex((item) => item.id === row.id);
      //查看未分配资产中是否存在已选中数据,存在则给出index,不存在则为-1
      let noAssignIndex = dataSoureNoAssign.findIndex((item) => item.id === row.id);
      if (noAssignIndex > -1) {
        //如果存在并且未分配资产存在未分配数量，则累加
        if (dataSoureNoAssign[noAssignIndex].restNum !== null && dataSoureNoAssign[noAssignIndex].restNum !== '' && !isNaN(dataSoureNoAssign[noAssignIndex].restNum)) {
          dataSoureNoAssign[noAssignIndex].restNum += dataSoureAssigned[selectIndex].allocation;
          this.setState({
            dataSoureNoAssign_old: JSON.parse(JSON.stringify(dataSoureNoAssign)),
          });
        }
      } else {
        let rowObj = JSON.parse(JSON.stringify(row));
        rowObj.restNum = row.allocation; //数量 字段不一样 做一个调整
        rowObj.restAmount = row.price; //成本价 字段不一样 做一个调整
        //如果不存在 则直接push到未分配表格
        dataSoureNoAssign.unshift(rowObj);
        this.setState({
          dataSoureNoAssign_old: JSON.parse(JSON.stringify(dataSoureNoAssign)),
        });
      }
      //将选中数据从已分配资产列表中移除
      dataSoureAssigned.splice(selectIndex, 1);
    });
    //更新state里的数据
    this.setState({
      dataSoureAssigned: [...dataSoureAssigned],
      dataSoureNoAssign: [...dataSoureNoAssign],
      selectedRowKeysUp: undefined, //上方选中行index 已分配
      seletedRowsUp: [], //下方方选中行index 未分配
    });
  };
  //点击向上箭头
  onClickUp = () => {
    const { seletedRowsDown, dataSoureNoAssign, dataSoureAssigned, dataSourceAssignedOld } = this.state;
    if (!seletedRowsDown.length) return;
    if (dataSoureAssigned.findIndex((item) => item.isEdit == true) > -1) {
      message.warning('当前处于编辑状态!');
      return;
    }
    seletedRowsDown.map((row) => {
      // //找出当前选中的资产在未分配资产数组中的index位置 ，为了移动之后，删除该行
      // let selectIndex=dataSoureNoAssign.findIndex(item => item.key === row.key );
      //查看已分配资产中是否存在已选中数据,存在则给出index,不存在则为-1
      let assignIndex = dataSoureAssigned.findIndex((item) => item.key === row.key);
      if (assignIndex > -1) {
        //如果初始化后 添加过  则修改为可编辑
        dataSoureAssigned[assignIndex].allocation = 0; //数量和成本价可编辑，默认值是0；
        dataSoureAssigned[assignIndex].isEdit = true;
      } else {
        //如果不存在 直接push到已分配表格 并且数量设置为0
        let rowObj = JSON.parse(JSON.stringify(row));
        rowObj.allocation = 0; //数量可编辑，默认值是0；
        rowObj.isEdit = true;
        rowObj.price = row.restAmount; //成本价 字段不一样 做一个调整
        dataSoureAssigned.unshift(rowObj);
      }
    });
    //更新state里的数据
    this.setState({
      dataSoureAssigned: [...dataSoureAssigned],
      selectedRowKeysDown: undefined, //下方方选中行index 未分配
      seletedRowsDown: [],
    });
  };
  render() {
    const { loading, modalData } = this.props;
    const { columnsAssigned, dataSoureAssigned, assignedProportion, columnsNoAssign, dataSoureNoAssign, seletedRowsUp, seletedRowsDown, assetProductRate } = this.state;
    const { seriesProductId } = this.props;
    const modalProps = {
      visible: this.props.visible,
      onOk: () => {
        this.confirmCalc();
      },
      onCancel: () => {
        this.props.triggleVisible(false);
      },
      title: '手动调整',
      className: 'assignDiy',
      height: 630, //内容区域的高度
      width: 1114,
      maskClosable: false, //点击蒙层 不关闭
    };

    return (
      <div>
        <ModalC {...modalProps}>
          <div>
            <SecondHeaderC title={'产品信息'} />
          </div>
          <Row className='product_info_row'>
            <Col span={6}>
              <span>产品代码 :</span>
              <span>{modalData.productCode}</span>
            </Col>
            <Col span={6}>
              <span>产品名称 :</span>
              <span>{modalData.productName}</span>
            </Col>
            <Col span={6}>
              <span style={{ textAlign: 'right', width: '76px', display: 'inline-block' }}>募集规模 :</span>
              <span>{modalData.raisedMoney}</span>
            </Col>
            <Col span={6}>
              <span style={{ textAlign: 'right', width: '105px', display: 'inline-block' }}>预期收益率 :</span>
              <span>{modalData.expectedRate !== undefined && modalData.expectedRate !== null ? fixedNum(parseFloat(modalData.expectedRate * 100), 2) + '%' : '--'}</span>
            </Col>
          </Row>
          <Row className='product_info_row'>
            <Col span={6}>
              <span>起息日期 :</span>
              <span>{modalData.startDate}</span>
            </Col>
            <Col span={6}>
              <span>到期日期 :</span>
              <span>{modalData.endDate}</span>
            </Col>
            <Col span={6}>
              <span>已分配比例 :</span>
              <span>{assignedProportion !== undefined && assignedProportion !== null ? fixedNum(parseFloat(assignedProportion * 100), 2) + '%' : '--'}</span>
            </Col>
            <Col span={6}>
              <span>资产组合收益率 :</span>
              <span>{assetProductRate !== undefined && assetProductRate !== null ? fixedNum(parseFloat(assetProductRate * 100), 2) + '%' : '--'}</span>
            </Col>
          </Row>
          <div style={{ marginTop: '20px' }}>
            <SecondHeaderC title={'资产分配'} />
          </div>
          <Spin spinning={(loading.effects['initialSplitM/tryCalc'] || loading.effects['initialSplitM/confirmCalc']) == true} tip='加载中...'>
            <div style={{ marginBottom: '10px' }}>
              <PrimaryC
                title={'试算'}
                onClick={() => {
                  this.tryCalc();
                }}
                disabled={dataSoureAssigned && dataSoureAssigned.length ? false : true}
              />
            </div>
            <div className='assigned'>
              <div className='assignTitle'>已分配</div>
              {this.initTableAssigned()}
            </div>
            <div className={'upDownDiv'}>
              <img src={seletedRowsDown.length ? upSelectedImg : upImg} onClick={this.onClickUp} />
              <img src={seletedRowsUp.length ? downSelectedImg : downImg} onClick={this.onClickDown} />
            </div>
            <div className='assigned'>
              <div className='assignTitle'>未分配</div>
              {columnsNoAssign && dataSoureNoAssign ? this.initTableNoAssign() : <NoQueryC />}
            </div>
          </Spin>
        </ModalC>
      </div>
    );
  }
}
